#include "camera.h"
#include "tachometerui.h"

#define DATA "POS1"


Camera::Camera(QObject *parent) : SocketBase(parent)
{
    isNewImage = false;
    connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(sendRequest()));
    timer->start(100);

    image = cvCreateImage(cvSize(640, 480), 8, 3);

    positions.anzahlObjekte = 0;
}

Camera::~Camera()
{
    cvReleaseImage(&image);
}

ObjektListe* Camera::getPositions()
{
    return &positions;
}

IplImage* Camera::getImage()
{
    return image;
}

void Camera::sendRequest()
{
    packetToWrite.cmd = OBJECTS_REQUEST;
    writeData();
}

void Camera::writeData()
{
    if (socket->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data;
        QDataStream out(&data, QIODevice::WriteOnly);
        out.setVersion(QDataStream::BigEndian);
        //out.writeRawData((const char*) (&packetToWrite), comandPkgSize);
        out.writeRawData(DATA, sizeof(DATA));
        socket->write(data);
    }
}

void Camera::readData()
{
    QDataStream in(socket);
    in.setVersion(QDataStream::BigEndian);

    //logTextEdit->append(tr("LOG: new data received: %1 bytes").arg(socket->bytesAvailable()));
    if (!isNewImage) {
        if (socket->bytesAvailable() >= (objektListeSize + imageSize))
        {
            in.readRawData((char*) (&positions), objektListeSize);
            if(ProzessLeitSystem::instanze->camLogCheckBox() && 0)
            {
            for(int i = 0; i < positions.anzahlObjekte; ++i)
            {
                logTextEdit->append(tr("id:%1 x:%2 y:%3 t:%4")
                                    .arg(positions.kord[i].objektId)
                                    .arg(positions.kord[i].xkordinate_mm)
                                    .arg(positions.kord[i].ykordinate_mm)
                                    .arg(positions.kord[i].theta_grad));
            }
        }
            newImage = new IplImage();
            in.readRawData((char*) (newImage), imageSize);
            newImage->imageData = NULL;
            isNewImage = true;
            //logTextEdit->append(tr("LOG: data processed: %1 %2").arg(packetToRead.command).arg(packetToRead.speed));
        }
    } else {
        if (socket->bytesAvailable() >= newImage->imageSize) {
            IplImage *tmp = cvCreateImage(cvSize(newImage->width, newImage->height),
                                          newImage->depth, newImage->nChannels);
            in.readRawData((char*) (tmp->imageData), newImage->imageSize);
            cvReleaseImage(&image);
            image = cvCloneImage(tmp);
            cvReleaseImage(&tmp);
            isNewImage = false;
        }
    }
}
